import React, { Fragment } from 'react'
import { View, StyleSheet, Text } from 'react-native'
import { connect } from 'react-redux'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import BaseManager from 'src/pageP/base/base-manager'
import TipPromptComp from 'src/components/tip-prompt/TipPrompt'
import CustomImage from 'src/components/image/CustomImage'
import CustomButton from 'src/components/button/CustomButton'
import showPicker from 'src/utils/PickerUtil'
import {
  DO_REQUEST_DEL_WORK,
  DO_REQUEST_INSERT_WORK, DO_REQUEST_UPDATE_WORK,
  DO_REQUEST_USER_ARCHIVE_WORK, UPDATE_USER_ARCHIVE_WORK_ACTION
} from '../../mine/mine-page/store/action'
import { CommonToast } from 'src/utils/ToastUtil'
import {
  generateFullTimeByYearMonth, generateYearFromNow, getMonthFromFullTime, getMonths, getMonthStrFromFullTime,
  getYearFromFullTime
} from 'src/utils/TimeUtil'
import { companyListByKeyword } from '../../../utils/RequestAPI'
import CustomTextEllipsize from '../../../components/custom-text-ellipsize/index'
import { showTipModal } from '../../../utils/ModalUtil'

const arrowRightImg = require('@/imgC/userinfo/arrow_black_right.png')
// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserArchiveWork (payload) {
    dispatch(UPDATE_USER_ARCHIVE_WORK_ACTION(payload))
  },
  doRequestUserArchiveWork (payload) {
    const promise = DO_REQUEST_USER_ARCHIVE_WORK(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestInsertWork (payload) {
    const promise = DO_REQUEST_INSERT_WORK(payload)
    return promise.payload
  },
  doRequestUpdateWork (payload) {
    const promise = DO_REQUEST_UPDATE_WORK(payload)
    return promise.payload
  },
  doRequestDelWork (payload) {
    const promise = DO_REQUEST_DEL_WORK(payload)
    return promise.payload
  }
})

@connect(state => state, mapDispatchToProps)
class CWorkExperienceManager extends BaseManager {
  constructor (props) {
    super(props)
    const {
      navigation: {
        state: { params }
      }
    } = this.props
    this.state = {
      ...this.state,
      workExperience: (params && params.workExperience) || null
    }
    this.titleText = '工作经验'
    this.completeText = '删除本条'
    this.config = {
      onCancel: this.onCancel,
      onConfirm: this.onConfirm,
      contentText: '确定删除这段工作经历吗？'
    }
    this.showDeleteCompleteBtn = params && params.showDelete
    this.years = generateYearFromNow(50)
    this.months = getMonths()
    this.isEditWork = params
  }

  onSave = () => {
    const { doRequestInsertWork, doRequestUpdateWork, userinfo, CMineCenterStore } = this.props
    const { workExperience } = this.state
    if (workExperience) {
      if (!workExperience.companyName) {
        CommonToast('请填写公司名称')
        return
      }
      if (!workExperience.positionName) {
        CommonToast('请填写工作职位')
        return
      }
      if (!workExperience.beginTime) {
        CommonToast('请选择开始时间')
        return
      }
      if (!workExperience.endTime) {
        CommonToast('请选择结束时间')
        return
      }
      if (!workExperience.achievement) {
        CommonToast('请填写工作描述')
        return
      }
    } else {
      CommonToast('请完善工作经历')
      return
    }
    const paramsWork = {
      beginTime: workExperience.beginTime,
      positionName: workExperience.positionName,
      endTime: workExperience.endTime,
      companyName: workExperience.companyName,
      achievement: workExperience.achievement,
      userId: userinfo.userId
    }
    if (this.isEditWork) {
      paramsWork.id = workExperience.id
      doRequestUpdateWork(paramsWork).then((workExperience) => {
        CommonToast('更新成功')
        const userArchiveWorkModels = CMineCenterStore.userArchiveWorkModels.map((item) => {
          return item.id === workExperience.id ? workExperience : item
        })
        this._updateWork(userArchiveWorkModels)
      })
    } else {
      doRequestInsertWork(paramsWork).then((workExperience) => {
        CommonToast('添加成功')
        const userArchiveWorkModels = CMineCenterStore.userArchiveWorkModels.concat(workExperience)
        this._updateWork(userArchiveWorkModels)
      })
    }
  }

  _updateWork = (userArchiveWorkModels) => {
    const { updateUserArchiveWork, CMineCenterStore, navigation } = this.props
    updateUserArchiveWork({
      userArchiveWorkModels
    })
    if (CMineCenterStore.userArchiveWorkModels.length > 0) {
      navigation.goBack()
    } else {
      navigation.navigate('CMainTab')
    }
  }

  childContentRender () {
    const { workExperience } = this.state
    return (
      <Fragment>
        <CustomButton style={styles.itemView} onPress={this._goCompanyName}>
          <View style={styles.itemContentView}>
            <Text style={styles.leftLabel}>公司名称</Text>
            <CustomTextEllipsize
              style={styles.rightLabel}
              text={(workExperience && workExperience.companyName) || '请输入'}/>
            <CustomImage style={styles.rightImg} source={arrowRightImg}/>
          </View>
          <View style={styles.itemLine}/>
        </CustomButton>
        <CustomButton style={styles.itemView} onPress={this._goJobName}>
          <View style={styles.itemContentView}>
            <Text style={styles.leftLabel}>工作职位</Text>
            <Text style={styles.rightLabel}>{(workExperience && workExperience.positionName) || '请输入'}</Text>
            <CustomImage style={styles.rightImg} source={arrowRightImg}/>
          </View>
          <View style={styles.itemLine}/>
        </CustomButton>
        <CustomButton
          style={styles.itemView}
          onPress={this._showPickerByType}
          params={{ type: 'beginTime', title: '开始时间' }}>
          <View style={styles.itemContentView}>
            <Text style={styles.leftLabel}>开始时间</Text>
            <Text
              style={styles.rightLabel}>{(workExperience && workExperience.beginTime) ? `${getYearFromFullTime(workExperience.beginTime)}.${getMonthStrFromFullTime(workExperience.beginTime)}` : '请选择'}</Text>
            <CustomImage style={styles.rightImg} source={arrowRightImg}/>
          </View>
          <View style={styles.itemLine}/>
        </CustomButton>
        <CustomButton
          style={styles.itemView}
          onPress={this._showPickerByType}
          params={{ type: 'endTime', title: '结束时间' }}>
          <View style={styles.itemContentView}>
            <Text style={styles.leftLabel}>结束时间</Text>
            <Text
              style={styles.rightLabel}>{(workExperience && workExperience.endTime) ? `${getYearFromFullTime(workExperience.endTime)}.${getMonthStrFromFullTime(workExperience.endTime)}` : '请选择'}</Text>
            <CustomImage style={styles.rightImg} source={arrowRightImg}/>
          </View>
          <View style={styles.itemLine}/>
        </CustomButton>
        <CustomButton style={styles.itemView} onPress={this._achievement}>
          <View style={styles.itemContentView}>
            <Text style={styles.leftLabel}>工作描述</Text>
            <CustomTextEllipsize
              style={styles.rightLabel}
              text={(workExperience && workExperience.achievement) || '请输入'}
            />
            <CustomImage style={styles.rightImg} source={arrowRightImg}/>
          </View>
          <View style={styles.itemLine}/>
        </CustomButton>
      </Fragment>
    )
  }

  onCancel = () => {
    this.toggleTipPrompt(false)
  }

  onConfirm = () => {
    this.toggleTipPrompt(false, this._deleteWork)
  }

  onComplete () {
    console.info('onComplete')
    this.toggleTipPrompt(true)
  }

  _deleteWork = () => {
    const { doRequestDelWork, userinfo, CMineCenterStore } = this.props
    const { workExperience } = this.state
    const paramsWork = {
      id: workExperience.id,
      userId: userinfo.userId
    }
    doRequestDelWork(paramsWork).then(() => {
      CommonToast('删除成功')
      const userArchiveWorkModels = CMineCenterStore.userArchiveWorkModels.filter((item) => {
        return item.id !== workExperience.id
      })
      this._updateWork(userArchiveWorkModels)
    })
  }

  toggleTipPrompt = (showTip, callBack) => {
    if (showTip) {
      this.tipModal = showTipModal(this.config)
    } else {
      if (this.tipModal) {
        this.tipModal.close(() => {
          callBack && callBack()
        })
      }
    }
  }

  _showPickerByType = ({ type, title }) => {
    const { workExperience } = this.state
    const onPickerConfirm = this._onPickerConfirm
    this._onPickerConfirm.type = type
    const selectedValue = workExperience && workExperience[type] ? [getYearFromFullTime(workExperience[type]), getMonthFromFullTime(workExperience[type])] : []
    // if (type === 'endTime') {
    //   this.years.unshift('至今')
    // }
    this._showPicker(selectedValue, onPickerConfirm, title)
  }

  _showPicker = (selectedValue, onPickerConfirm, pickerTitleText) => {
    showPicker({
      pickerData: [this.years, this.months],
      selectedValue: selectedValue,
      pickerTitleText,
      onConfirm: onPickerConfirm
    })
  }

  _onPickerConfirm = (data) => {
    const { workExperience } = this.state
    switch (this._onPickerConfirm.type) {
      case 'beginTime':
        if (workExperience && workExperience.endTime && generateFullTimeByYearMonth(data[0], data[1]) > workExperience.endTime) {
          CommonToast('开始时间不能大于结束时间')
          return
        }
        break
      case 'endTime':
        if (workExperience && workExperience.beginTime && generateFullTimeByYearMonth(data[0], data[1]) < workExperience.beginTime) {
          CommonToast('结束时间不能小于开始时间')
          return
        }
        break
    }
    this._setWorkExperience({
      [this._onPickerConfirm.type]: generateFullTimeByYearMonth(data[0], data[1])
    })
  }

  _goCompanyName = () => {
    const { workExperience } = this.state
    this.props.navigation.navigate('CommonInputListPage', {
      title: '公司名称',
      value: workExperience ? workExperience.companyName : '',
      desc: '*支持全国所有公司名称',
      placeholder: '请输入公司名称',
      maxLength: 46,
      saveCallback: this._companySave,
      associativeRequest: this._companyAssociative
    })
  }

  _companySave = (value) => {
    this._setWorkExperience({
      companyName: value
    })
  }

  _companyAssociative = (keyword) => {
    return new Promise((resolve) => {
      companyListByKeyword({ params: { keyword } }).then(res => {
        const newDataArr = res.data.map(e => ({
          ...e,
          name: e.name.replace(/<(?:.|\s)*?>/g, '')
        }))
        resolve(newDataArr)
      })
    })
  }

  _goJobName = () => {
    const { workExperience } = this.state
    this.props.navigation.navigate('CommonInputPage', {
      title: '职位名称',
      value: workExperience ? workExperience.positionName : '',
      desc: '*公司组织架构的岗位名称',
      placeholder: '请输入职位名称',
      maxLength: 8,
      saveCallback: this._positionSave
    })
  }

  _positionSave = (value) => {
    this._setWorkExperience({
      positionName: value
    })
  }

  _achievement = () => {
    const { workExperience } = this.state
    this.props.navigation.navigate('WorkDescriptionPage', {
      title: '工作描述',
      value: workExperience ? workExperience.achievement : '',
      desc: '*不能填联系方式以及特殊符号',
      placeholder: '请输入工作描述',
      maxLength: 2000,
      saveCallback: this._achievementSave
    })
  }

  _achievementSave = (value) => {
    this._setWorkExperience({
      achievement: value
    })
  }

  _setWorkExperience = (otherWorkExperience) => {
    const { workExperience } = this.state
    this.setState({
      workExperience: {
        ...workExperience,
        ...otherWorkExperience
      }
    })
  }
}

export default CWorkExperienceManager

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  itemView: {
    height: ScaleS(76),
    paddingHorizontal: ScaleS(20)
  },
  itemContentView: {
    height: ScaleS(75),
    flexDirection: 'row',
    alignItems: 'center'
  },
  leftLabel: {
    color: '#444444',
    fontSize: ScaleT(16),
    fontWeight: '600',
    flex: 1
  },
  rightLabel: {
    color: '#444444',
    fontSize: ScaleT(16),
    fontWeight: '400',
    marginRight: ScaleS(16),
    maxWidth: ScaleS(230)
  },
  rightImg: {
    width: ScaleS(6),
    height: ScaleS(12)
  },
  itemLine: {
    height: ScaleS(1),
    backgroundColor: '#EFEFEF'
  }
})
